package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.handler;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyByteBuf;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

/**
 * 来自客户端 真实服务器返回的数据请求
 */
@Slf4j
public class NettyHttpServerProxyClientRealHandler extends SimpleChannelInboundHandler<NettyByteBuf> {


    @Override
    public void channelRead0(ChannelHandlerContext ctx,NettyByteBuf nettyByteBuf) {

        byte[] bytes = nettyByteBuf.getData();
        log.debug("bytes.length:{}",bytes.length);
        log.debug("客户端代理客户端，接收目标客户端真实服务数据:{}", new String(bytes));
        String visitorId = ChannelAttributeKeyUtils.getVisitorId(ctx.channel());
        String clientId = ChannelAttributeKeyUtils.getClientId(ctx.channel());
        // 访客通信通道 上报服务端代理完成
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(ctx.channel());
        NettyProxyMsg returnMessage = new NettyProxyMsg();
        returnMessage.setType(ProxyMessageType.HTTP_REPORT_SERVER_PROXY_CLIENT_TRANSFER_RESPONSE_);
        returnMessage.setVisitorId(visitorId);
        returnMessage.setClientId(clientId);
        returnMessage.setData(bytes);

        nextChannel.writeAndFlush(returnMessage);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String visitorId = ChannelAttributeKeyUtils.getVisitorId(ctx.channel());
        //  客户端真实通信通道
        Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(ctx.channel());
        if (nextChannel != null) {
            // 上报关闭这个客户端的访客通道
            NettyProxyMsg closeVisitorMsg = new NettyProxyMsg();
            closeVisitorMsg.setType(ProxyMessageType.HTTP_REPORT_SERVER_PROXY_CLIENT_TRANSFER_CLOSE_);
            closeVisitorMsg.setVisitorId(visitorId);
            nextChannel.writeAndFlush(closeVisitorMsg);
        }

        super.channelInactive(ctx);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        // 获取访客的传输通道
        if (ctx.channel().isWritable()) {
            log.debug("Channel is writable again");
            // 恢复之前暂停的操作，如写入数据
        } else {
            log.debug("Channel is not writable");
            // 暂停写入操作，等待可写状态
        }
        log.info("channelWritabilityChanged!");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}